import { Subject, Subscription } from 'rxjs';

/**
 * @description 控制器基类
 * @export
 * @class AppUIControllerBase
 */
export class AppUIControllerBase {
  /**
   * @description 自定义事件传递对象
   * @type {Subject<{ eventName: string, args: any }>}
   * @memberof AppUIControllerBase
   */
  public customEventState: Subject<{ eventName: string; args: any }> = new Subject();

  /**
   * @description 自定义事件订阅对象
   * @type {(Subscription | undefined)}
   * @memberof AppUIControllerBase
   */
  public customStateEvent: Subscription | undefined;

  /**
   * @description 自定义事件Map
   * @type {Map<string, Function>}
   * @memberof AppUIControllerBase
   */
  public customEventMap: Map<string, Function> = new Map();

  /**
   * Creates an instance of AppUIControllerBase.
   * @param {*} opts
   * @memberof AppUIControllerBase
   */
  constructor(opts: any) {
    this.executeCallBack();
  }

  /**
   * @description 挂载事件
   * @param {string} eventName
   * @param {Function} callback
   * @memberof AppUIControllerBase
   */
  public on(eventName: string, callback: Function) {
    this.customEventMap.set(eventName, callback);
  }

  /**
   * @description 触发事件
   * @param {string} eventName
   * @param {Function} callback
   * @memberof AppUIControllerBase
   */
  public emit(eventName: string, args: any) {
    this.customEventState.next({ eventName: eventName, args: args });
  }

  /**
   * @description 执行回调
   * @memberof AppUIControllerBase
   */
  public executeCallBack() {
    this.customStateEvent = this.customEventState.subscribe(({ eventName, args }: { eventName: string; args: any }) => {
      if (this.customEventMap.get(eventName)) {
        (this.customEventMap.get(eventName) as Function)(args);
      }
    });
  }

  /**
   * @description 取消订阅
   * @memberof AppUIControllerBase
   */
  public cancelSubscribe() {
    if (this.customStateEvent) {
      this.customStateEvent.unsubscribe();
    }
  }
}
